//
//  LoginViewController.m
//  Gunz
//
//  Created by Joggy on 16/1/20.
//  Copyright © 2016年 NUPT. All rights reserved.
//

#import "LoginViewController.h"
#import "AppDelegate.h"
#import "GZFilePath.h"
#import "QYNotice.h"
#import "CoreStatus.h"

@interface LoginViewController ()

@end

@implementation LoginViewController

static CGRect viewOrigin;
static CGFloat textFieldBottom;

- (void)viewDidLoad {
    [super viewDidLoad];
    lv = [[LoginView alloc] initWithFrame:CGRectMake(0, 0, screenWidth, screenHeight)];
    [[self view] addSubview:lv];
    //添加代理
    lv.nameTextField.delegate = self;
    lv.passwordTextField.delegate = self;
    //添加事件
    [lv.loginButton addTarget:self action:@selector(login) forControlEvents:UIControlEventTouchUpInside];
    [lv.findPWButton addTarget:self action:@selector(findPassword) forControlEvents:UIControlEventTouchUpInside];
    [lv.registerButton addTarget:self action:@selector(registerUser) forControlEvents:UIControlEventTouchUpInside];
    [lv.rememberButton addTarget:self action:@selector(isRememberPass:) forControlEvents:UIControlEventTouchUpInside];
    [lv.autoLoginButton addTarget:self action:@selector(isAutoLogin:) forControlEvents:UIControlEventTouchUpInside];
    if([GZLoginState isLogin]) {
        GZLoginState *user = [GZLoginState shareInstance];
        if(user.autoLoginState) {
            lv.autoLoginButton.selected = true;
        }
        else {
            lv.autoLoginButton.selected = false;
        }
        if(user.rememberPasswordState) {
            lv.rememberButton.selected = true;
            lv.nameTextField.text = user.loginAccount;
            lv.passwordTextField.text = user.password;
        }
        else {
            lv.rememberButton.selected = false;
        }
    }
    //注册
    registerSheet = [[LGActionSheet alloc] initWithFrame:CGRectMake(0, screenHeight, screenWidth, bgHeight)];
    [registerSheet.registerByPhoneButton addTarget:self action:@selector(registerByPhone) forControlEvents:UIControlEventTouchUpInside];
    [registerSheet.registerByEmailButton addTarget:self action:@selector(registerByEmail) forControlEvents:UIControlEventTouchUpInside];
    [registerSheet.cancelButton addTarget: self action:@selector(cancel) forControlEvents:UIControlEventTouchUpInside];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    if(lv != nil) {
        viewOrigin = lv.frame;
    }
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)isRememberPass:(UIButton*)sender {
    sender.selected = !sender.selected;
}

- (void)isAutoLogin:(UIButton*)sender {
    sender.selected = !sender.selected;
}

- (NSString*)collectData {
    if([lv.nameTextField.text isEqualToString:@""]) {
        return @"请输入账号";
    }
    else if([lv.passwordTextField.text isEqualToString:@""]) {
        return @"请输入密码";
    }
    _data = @{@"username": lv.nameTextField.text, @"password": lv.passwordTextField.text};
    return @"noerror";
}

- (void)login {
    if([CoreStatus isNetworkEnable]) {
        NSString *status = [self collectData];
        if([status isEqualToString:@"noerror"]) {
            AFHTTPSessionManager *manager = [GZNetRequest getPOSTManager];
            NSString *url = [GZNetRequest getLoginURL];
            [manager POST:url parameters:_data progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                NSDictionary *data = (NSDictionary*)responseObject;
                if([data[@"status"] isEqualToString:@"success"]) {
                    NSDictionary *msg = (NSDictionary*)data[@"msg"][0];
                    [GZLoginState setCurrentLoginUserID:msg[@"pk"]];
                    NSDictionary *fields = (NSDictionary*)msg[@"fields"];
                    GZLoginState *user = [GZLoginState shareInstance];
                    [user setLoginAccount:_data[@"username"]];
                    [user setPassword:_data[@"password"]];
                    [user setUserName:fields[@"nickname"]];
                    [user setUserSex:fields[@"sex"]];
                    [user setIntroduce:fields[@"favourit"]];
                    [user setIsReal:fields[@"isreal"]];
                    [user setReputation:fields[@"reputation"]];
                    [user setGunzCoin:@""];
                    [user setBalance:@""];
                    [user setPhone:fields[@"phone"]];
                    [user setEmail:fields[@"email"]];
                    [user setRememberPasswordState:lv.rememberButton.selected];
                    [user setAutoLoginState:lv.autoLoginButton.selected];
                    [user updateUserInfo];
                    [GZLoginState setLoginState:true];
                    [GZLoginState createUserDucomentByUserID:[GZLoginState getCurrentLoginUserID]];
                    [UIView animateWithDuration:0.3 delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{
                        lv.transform = CGAffineTransformMakeScale(1.2, 1.2);
                    } completion:^(BOOL finished) {
                        AppDelegate *app = [UIApplication sharedApplication].delegate;
                        app.window.rootViewController = app.vc;
                        lv.transform = CGAffineTransformMakeScale(1, 1);
                    }];
                }
                else {
                    [QYNotice showError:@"用户名或密码错误" toView:lv.noticeView];
                    [QYNotice dismissWithDelay:3];
                }
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                NSLog(@"%@", error);
                [QYNotice showError:@"未连接到服务器" toView:lv.noticeView];
                [QYNotice dismissWithDelay:3];
            }];
        }
        else {
            [QYNotice showError:status toView:lv.noticeView];
            [QYNotice dismissWithDelay:3];
        }
    }
    else {
        [QYNotice showWarning:@"未检测到网络" toView:lv.noticeView];
        [QYNotice dismissWithDelay:3];
    }
}

- (void)findPassword {
    NSLog(@"忘记密码");
    FPViewController *findPassword = [[FPViewController alloc] init];
    UINavigationController *findNav = [[UINavigationController alloc] initWithRootViewController:findPassword];
    [self presentViewController:findNav animated:true completion:nil];
}

- (void)registerUser {
    [registerSheet show];
}

- (void)registerByPhone {
    NSLog(@"手机号注册");
    RGPhoneViewController *phoneReg = [[RGPhoneViewController alloc] init];
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:phoneReg];
    [self presentViewController:nav animated:true completion:nil];
    [registerSheet dismiss];
}

- (void)registerByEmail {
    NSLog(@"邮箱注册");
    RGEmailViewController *emailReg = [[RGEmailViewController alloc] init];
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:emailReg];
    [self presentViewController:nav animated:true completion:nil];
    [registerSheet dismiss];
}

- (void)cancel {
    [registerSheet dismiss];
}

- (void)keyboardWillShow:(NSNotification*)notification {
    NSDictionary *notifiInfo = notification.userInfo;
    CGFloat keyboardHeight = [[notifiInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size.height;
    CGFloat adjust = textFieldBottom - (screenHeight - keyboardHeight);
    [UIView animateWithDuration:0.3 animations:^{
        CGRect temp = viewOrigin;
        if(adjust > 0) {
            temp.origin.y -= adjust;
            lv.frame = temp;
        }
        else {
            lv.frame = viewOrigin;
        }
    }];
}

- (void)keyboardWillHide:(NSNotification*)notification {
    [UIView animateWithDuration:0.3 animations:^{
        lv.frame = viewOrigin;
    }];
}

#pragma textField代理方法

- (void)textFieldDidBeginEditing:(UITextField *)textField {
    if (textField.tag == 1) {
        textFieldBottom = lv.nameView.frame.origin.y + textField.frame.origin.y + textField.frame.size.height;
    }
    else if (textField.tag == 2) {
        textFieldBottom = lv.passwordView.frame.origin.y + textField.frame.origin.y + textField.frame.size.height;
    }
    else {
        textFieldBottom = 0;
    }
}

@end
